package com.example.smartcity.search;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

public class HotSearchFlowLayout extends ViewGroup {

    private final int mColumnCount = 2; // 设定列数为2

    public HotSearchFlowLayout(Context context) {
        super(context);
    }

    // 重载构造函数以支持XML布局
    public HotSearchFlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HotSearchFlowLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = 0;
        int height = 0;
        int childCount = getChildCount();
        int columnWidth = 0;

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        // 每列的宽度是总宽度除以列数
        columnWidth = (widthSize - getPaddingLeft() - getPaddingRight()) / mColumnCount;

        // 已用的列高度
        int[] columnHeights = new int[mColumnCount];

        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);

            // 首先测量子元素
            measureChild(child, widthMeasureSpec, heightMeasureSpec);

            // 计算宽度和高度
            width = Math.max(width, child.getMeasuredWidth());

            // 累加到对应的列高度
            columnHeights[i % mColumnCount] += child.getMeasuredHeight();
        }

        // 找出最高的列用于总高度
        for (int i = 0; i < mColumnCount; i++) {
            height = Math.max(height, columnHeights[i]);
        }

        // 加上padding和间距
        height += getPaddingTop() + getPaddingBottom();

        // 设置总体尺寸
        setMeasuredDimension(resolveSize(width, widthMeasureSpec), resolveSize(height, heightMeasureSpec));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        int columnWidth = (r - l) / mColumnCount;

        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();

        int[] columnHeights = new int[mColumnCount];

        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);

            // 计算子视图的left和top位置
            int lc = (i % mColumnCount) * columnWidth + paddingLeft;
            int tc = columnHeights[i % mColumnCount] + paddingTop;

            // 累加到对应的列高度
            columnHeights[i % mColumnCount] += child.getMeasuredHeight();

            // 定义子视图的位置
            child.layout(lc, tc, lc + child.getMeasuredWidth(), tc + child.getMeasuredHeight());
        }
    }
}